import debounce from "https://cdn.jsdelivr.net/npm/lodash-es/debounce.js";
let promise = Promise.resolve();
const talk = debounce((text) => {
    promise = promise.then(
        () =>
            new Promise((resolve) => {
                mui.toast(text, { duration: 2000 });
                setTimeout(() => resolve(), 2000);
                buffer = [];
            })
    );
}, 500);
let buffer = [];
window.Speak = (text) => {
    buffer.push(text);
    talk(buffer.join("\n"));
};
window.Record = {
    FlowerName: Mock.Random.cname(),
    stateCount: 0,
    nowState: {
        day: 0,
        step: stateMap[0].step,
        water: 0,
        fei: 0,
        drug: 0,
        diedTime: 0,
    },
    updateState(func) {
        const oldDay = this.nowState.day;
        func(this.nowState);

        this.checkAction(this.nowState.day !== oldDay);
    },
    DiedMessage: {
        water: "试着适量浇水吧",
        fei: "试着适量施肥吧",
        drug: "试着适量除虫吧",
        condition: "试着多照顾一下它吧",
    },
    Died(name) {
        document.documentElement.style.filter = "grayscale(100%)";
        const text = this.DiedMessage[name];
        Swal.fire({
            title: `${Record.FlowerName} 枯萎了`,
            text,
            imageUrl:
                app.stage.Flower.textures[app.stage.Flower.currentFrame]
                    .textureCacheIds[0],
            imageHeight: 300,
            confirmButtonText: "花生重开",
        }).then((res) => {
            location.reload();
        });
    },
    CheckAndSpeak(name, aSpeak, bSpeak) {
        const [maxNeed, maxSafe] = stateMap[this.stateCount][name];
        console.log(this.nowState[name], maxNeed, maxSafe);

        if (this.nowState[name] < maxNeed) {
            Speak(aSpeak);
        } else if (this.nowState[name] < maxSafe) {
            Speak(bSpeak);
            return true;
        } else if (this.nowState[name] > maxSafe) {
            this.Died(name);
        }
        return maxNeed === 0;
    },
    async Upgrade() {
        this.stateCount++;
        app.stage.Flower.changeStates(this.stateCount + "");
        if (this.stateCount < 7) {
            const text = stateMap[this.stateCount].text;
            this.stack = ["water", "day", "fei", "drug"].reduce((col, cur) => {
                col[cur] = this.nowState[cur] + this.stack[cur];
                this.nowState[cur] = 0;
                return col;
            }, {});
            this.nowState.step = stateMap[this.stateCount].step;
            Swal.fire({
                title: `${Record.FlowerName} 到了 ${
                    stateMap[this.stateCount].name
                } 阶段`,
                text,
                imageUrl: app.stage.Flower.textures[0].textureCacheIds[0],
                imageHeight: 300,
                confirmButtonText: "确认",
                timer: 2000,
            });
        } else {
            Swal.fire({
                title: `${Record.FlowerName} 完成了使命，孕育了新生命!`,
                text: "你获得了一袋 凤仙花 的种子",
                imageUrl: "./image/Flower/Seed.webp",
                imageHeight: 200,
                confirmButtonText: "再次播种",
            }).then((res) => {
                location.reload();
            });
        }
    },
    checkAction(dayChange = false) {
        const { name, day, water, fei, drug } = stateMap[this.stateCount];
        console.log(day, this.nowState.day);
        let condition;
        if (this.nowState.day < 100) {
            condition = [
                ["water", "我还需要水", "我喝饱了"],
                ["fei", "我还想吃东西", "我吃饱了"],
                ["drug", "我被虫子咬了", ""],
            ].map((i) => this.CheckAndSpeak(...i));
        }

        if (this.nowState.day >= day) {
            console.log(condition);
            if (this.nowState.day > 100 || condition.every((i) => i)) {
                // 进化了
                this.Upgrade();
                return;
            } else {
                this.Died("condition");
                return;
            }
        }
        if (dayChange) {
            const frame = app.stage.Flower.currentFrame + 1;

            if (app.stage.Flower.totalFrames > frame) {
                app.stage.Flower.gotoAndStop(frame);
                console.log("现在的 frame", frame);
            } else {
                console.log("超过了指定帧");
            }
        }
    },
    stack: {
        day: 0,
        water: 0,
        fei: 0,
        drug: 0,
        diedTime: 0,
    },
};
